<template>
  <div id="hospital">
    <div style="margin: 7px 0">
      <el-button
        type="primary"
        style="padding: 8px"
        size="small"
        icon="el-icon-circle-plus"
        @click="toAdd"
        >新增</el-button
      >
    </div>
    <div class="tableDiv">
      <el-table :data="tableData" style="width: 100%" max-height="540">
        <el-table-column align="center" type="index" label="序号" width="55">
        </el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="医院名称"
          width="210"
        >
        </el-table-column
        ><el-table-column
          align="center"
          prop="introduce"
          label="医院简介"
          width="170"
        >
        </el-table-column>
        <el-table-column align="center" label="所属地区" width="180">
          <template slot-scope="scope">
            {{ scope.row.province }}-{{ scope.row.city }}-{{ scope.row.area }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="医院地址"
          width="200"
        >
        </el-table-column
        ><el-table-column align="center" prop="flags" label="标记" width="70">
        </el-table-column>
        <el-table-column
          align="center"
          prop="longitude"
          label="经度"
          width="90"
        >
        </el-table-column>
        <el-table-column align="center" prop="latitude" label="纬度" width="90">
        </el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 翻页 -->
    <div>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="visible"
      :before-close="beforeClose"
    >
      <!-- 内层嵌套dialog -->
      <el-dialog
        width="80%"
        :title="'点击获取' + (form.name || '') + '经纬度'"
        :visible.sync="innerVisible"
        append-to-body
      >
        <!-- 点击新增按钮后 三步运算符中判定是否将地图定位定在本主机定位的条件应该是
      表单中是否已经存在了经度或者纬度 若已经存在 则无需再重新定位回本主机 -->
        <el-amap
          :center="
            form.longitude && form.latitude
              ? [form.longitude, form.latitude]
              : [currentPosition.longitude, currentPosition.latitude]
          "
          vid="amapDemo"
          :events="events"
          class="map"
        >
          <el-amap-marker
            vid="component-marker"
            :position="markerPosition"
          ></el-amap-marker
        ></el-amap>
      </el-dialog>
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="introduce"
          label="介绍"
          :label-width="formLabelWidth"
        >
          <el-input
            type="textarea"
            v-model="form.introduce"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pca" label="省市区" :label-width="formLabelWidth">
          <el-cascader
            @change="pcaChange"
            :props="{ value: 'label' }"
            v-model="form.pca"
            :options="regionData"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          prop="address"
          label="详细地址"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="flags" label="标记" :label-width="formLabelWidth">
          <el-input v-model="form.flags" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="longitude"
          label="经度"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.longitude" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="latitude"
          label="纬度"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.latitude" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCancel">取 消</el-button>
        <el-button type="primary" @click="innerVisible = true"
          >选取经纬度</el-button
        >
        <el-button type="primary" @click="toSave('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "../../utils/request";
import { regionData } from "element-china-area-data";
export default {
  data() {
    // var checkIsNull = (rule, value, callback) => {
    //   value = this.form.longitude;
    //   if (!value) {
    //     return callback(new Error("请输入经度"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      // 当前地理位置对象
      markerPosition: [],
      currentPosition: {},
      events: {
        click: (e) => {
          this.markerPosition = [e.lnglat.lng, e.lnglat.lat];
          this.form.longitude = e.lnglat.lng;
          this.form.latitude = e.lnglat.lat;
        },
      },
      innerVisible: false,
      regionData,
      total: 0,
      pageParam: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      multipleSelection: [],
      tableData: [],
      // 模态框可见性 dialog modal
      visible: false,
      // 模态框的数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "120px",
      // 模态框的标题
      title: "录入医院信息",
      // 表单校验规则
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        introduce: [{ required: true, message: "请输入介绍", trigger: "blur" }],
        pca: [{ required: true, message: "请选择省市区", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        flags: [{ required: true, message: "请输入标记", trigger: "blur" }],
        longitude: [
          {
            required: true,
            message: "请输入经度",
            trigger: "blur",
          },
          // { required: true, validator: checkIsNull, trigger: "blur" },
        ],
        latitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
      },
    };
  },
  computed: {},
  methods: {
    checkArea() {
      this.$refs["ruleForm"].resetFields("longitude");
    },
    pcaChange(val) {
      this.form = {
        ...this.form,
        province: val[0],
        city: val[1],
        area: val[2],
      };
    },
    handleSizeChange(val) {
      this.pageParam.pageSize = val;
      this.pageQuery();
    },
    handleCurrentChange(val) {
      this.pageParam.page = val;
      this.pageQuery();
    },
    // 关闭模态框
    toCancel() {
      this.$refs["ruleForm"].resetFields();
      this.visible = false;
    },
    // 模态框关闭之前
    beforeClose(done) {
      this.$refs["ruleForm"].resetFields();
      this.visible = false;
      done();
    },
    // 点击新增按钮
    toAdd() {
      this.form = {};
      this.markerPosition = [
        this.currentPosition.longitude,
        this.currentPosition.latitude,
      ];
      this.visible = true;
      this.title = "录入医院信息";
    },
    toSave(formName) {
      // 点击确定按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.form, "=====");
          axios.post("/hospital/saveOrUpdate", this.form).then((res) => {
            if (res.status == 200) {
              // 保存成功，关闭模态框，刷新数据，请求数据
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
              });
              this.toCancel();
              this.pageQuery();
            } else {
              this.$notify.error({
                title: "失败",
                message: "保存失败",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 编辑
    handleEdit(row) {
      // console.log(row);
      this.title = "编辑医院信息";
      this.form = { ...row, pca: [row.province, row.city, row.area] };
      this.markerPosition = [this.form.longitude, this.form.latitude];
      this.visible = true;
    },
    // 删除单个
    handleDelete(id) {
      // 要删除的医院的ID
      // await等待后面异步函数运行完毕 拿到响应的数据 然后返回
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 将拿到的id给接口
          let res = await axios.get("/hospital/deleteById", {
            params: { id },
          });
          this.$notify({
            title: res.status == 200 ? "成功" : "失败",
            message: res.statusText,
            type: (res.status = 200 ? "success" : "error"),
          });
          this.pageQuery();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分页查找
    async pageQuery() {
      let res = await axios.get("/hospital/pageQuery", {
        params: this.pageParam,
      });
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
  },
  created() {
    this.pageQuery();
    // 获取定位（一次）
    navigator.geolocation.getCurrentPosition(
      (data) => {
        // 信息都包含在data.coords里面
        this.currentPosition = data.coords;
        this.markerPosition = [
          this.currentPosition.longitude,
          this.currentPosition.latitude,
        ];
      },
      (err) => {
        console.log(err);
      },
      {
        enableHighAccuracy: true, //高精度
        timeout: 5000, //超时时间
        maximumAge: 10000, //位置缓存时间
      }
    );
  },
};
</script>
<style scoped>
#hospital {
  height: 100% !important;
}
.tableDiv {
  min-height: 540px;
}
.map {
  height: 300px;
}
</style>